<template>
  <div class="profile-container">
    <!-- 个人信息卡片 -->
    <div class="profile-header">
      <el-card class="profile-card">
        <div class="profile-info">
          <div class="avatar-section">
            <el-avatar :size="120" :src="userInfo.avatar || '/default-avatar.png'" />
            <el-button type="primary" size="small" @click="showAvatarDialog = true" class="change-avatar-btn">
              更换头像
            </el-button>
          </div>
          <div class="user-details">
            <h2>{{ userInfo.nickname || userInfo.username }}</h2>
            <p class="user-title">{{ getUserTypeText(userInfo.userType) }}</p>
            <div class="user-stats">
              <div class="stat-item">
                <span class="stat-number">{{ statistics.courseCount || 0 }}</span>
                <span class="stat-label">学习课程</span>
              </div>
              <div class="stat-item">
                <span class="stat-number">{{ statistics.examCount || 0 }}</span>
                <span class="stat-label">完成考试</span>
              </div>
              <div class="stat-item">
                <span class="stat-number">{{ statistics.studyHours || 0 }}</span>
                <span class="stat-label">学习时长(小时)</span>
              </div>
              <div class="stat-item">
                <span class="stat-number">{{ statistics.points || 0 }}</span>
                <span class="stat-label">学习积分</span>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 主要内容区域 -->
    <div class="profile-content">
      <el-row :gutter="20">
        <!-- 左侧菜单 -->
        <el-col :span="6">
          <el-card class="menu-card">
            <el-menu
              :default-active="activeMenu"
              @select="handleMenuSelect"
              class="profile-menu"
            >
              <el-menu-item index="basic">
                <el-icon><User /></el-icon>
                <span>基本信息</span>
              </el-menu-item>
              <el-menu-item index="security">
                <el-icon><Lock /></el-icon>
                <span>安全设置</span>
              </el-menu-item>
              <el-menu-item index="learning">
                <el-icon><Reading /></el-icon>
                <span>学习记录</span>
              </el-menu-item>
              <el-menu-item index="achievements">
                <el-icon><Trophy /></el-icon>
                <span>成就徽章</span>
              </el-menu-item>
              <el-menu-item index="settings">
                <el-icon><Setting /></el-icon>
                <span>偏好设置</span>
              </el-menu-item>
            </el-menu>
          </el-card>
        </el-col>

        <!-- 右侧内容 -->
        <el-col :span="18">
          <el-card class="content-card">
            <!-- 基本信息 -->
            <div v-if="activeMenu === 'basic'" class="content-section">
              <h3>基本信息</h3>
              <el-form :model="userForm" label-width="100px" class="profile-form">
                <el-form-item label="用户名">
                  <el-input v-model="userForm.username" disabled />
                </el-form-item>
                <el-form-item label="昵称">
                  <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
                </el-form-item>
                <el-form-item label="邮箱">
                  <el-input v-model="userForm.email" placeholder="请输入邮箱" />
                </el-form-item>
                <el-form-item label="手机号">
                  <el-input v-model="userForm.phone" placeholder="请输入手机号" />
                </el-form-item>
                <el-form-item label="性别">
                  <el-radio-group v-model="userForm.gender">
                    <el-radio label="MALE">男</el-radio>
                    <el-radio label="FEMALE">女</el-radio>
                    <el-radio label="UNKNOWN">保密</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="生日">
                  <el-date-picker
                    v-model="userForm.birthday"
                    type="date"
                    placeholder="请选择生日"
                    style="width: 100%"
                  />
                </el-form-item>
                <el-form-item label="个人简介">
                  <el-input
                    v-model="userForm.bio"
                    type="textarea"
                    :rows="4"
                    placeholder="介绍一下自己吧..."
                  />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="updateProfile" :loading="updating">
                    保存修改
                  </el-button>
                </el-form-item>
              </el-form>
            </div>

            <!-- 安全设置 -->
            <div v-if="activeMenu === 'security'" class="content-section">
              <h3>安全设置</h3>
              <div class="security-items">
                <div class="security-item">
                  <div class="security-info">
                    <h4>登录密码</h4>
                    <p>定期更换密码可以提高账户安全性</p>
                  </div>
                  <el-button @click="showPasswordDialog = true">修改密码</el-button>
                </div>
                <div class="security-item">
                  <div class="security-info">
                    <h4>手机绑定</h4>
                    <p>{{ userInfo.phone ? `已绑定：${userInfo.phone}` : '未绑定手机号' }}</p>
                  </div>
                  <el-button>{{ userInfo.phone ? '更换' : '绑定' }}手机</el-button>
                </div>
                <div class="security-item">
                  <div class="security-info">
                    <h4>邮箱绑定</h4>
                    <p>{{ userInfo.email ? `已绑定：${userInfo.email}` : '未绑定邮箱' }}</p>
                  </div>
                  <el-button>{{ userInfo.email ? '更换' : '绑定' }}邮箱</el-button>
                </div>
              </div>
            </div>

            <!-- 学习记录 -->
            <div v-if="activeMenu === 'learning'" class="content-section">
              <h3>学习记录</h3>
              <div class="learning-stats">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <div class="stat-card">
                      <h4>本周学习</h4>
                      <p class="stat-value">{{ weeklyStats.hours }}小时</p>
                    </div>
                  </el-col>
                  <el-col :span="8">
                    <div class="stat-card">
                      <h4>本月学习</h4>
                      <p class="stat-value">{{ monthlyStats.hours }}小时</p>
                    </div>
                  </el-col>
                  <el-col :span="8">
                    <div class="stat-card">
                      <h4>总学习时长</h4>
                      <p class="stat-value">{{ statistics.studyHours }}小时</p>
                    </div>
                  </el-col>
                </el-row>
              </div>
              
              <h4>最近学习课程</h4>
              <div class="recent-courses">
                <div v-for="course in recentCourses" :key="course.id" class="course-item">
                  <img :src="course.cover" :alt="course.title" class="course-cover" />
                  <div class="course-info">
                    <h5>{{ course.title }}</h5>
                    <p>学习进度：{{ course.progress }}%</p>
                    <p>最后学习：{{ formatDate(course.lastStudyTime) }}</p>
                  </div>
                  <el-button type="primary" size="small" @click="continueLearning(course)">
                    继续学习
                  </el-button>
                </div>
              </div>
            </div>

            <!-- 成就徽章 -->
            <div v-if="activeMenu === 'achievements'" class="content-section">
              <h3>成就徽章</h3>
              <div class="achievements-grid">
                <div v-for="achievement in achievements" :key="achievement.id" class="achievement-item">
                  <div class="achievement-icon" :class="{ unlocked: achievement.unlocked }">
                    <el-icon :size="40">
                      <component :is="achievement.icon" />
                    </el-icon>
                  </div>
                  <h5>{{ achievement.name }}</h5>
                  <p>{{ achievement.description }}</p>
                  <span v-if="achievement.unlocked" class="unlock-date">
                    {{ formatDate(achievement.unlockDate) }}
                  </span>
                </div>
              </div>
            </div>

            <!-- 偏好设置 -->
            <div v-if="activeMenu === 'settings'" class="content-section">
              <h3>偏好设置</h3>
              <el-form :model="settingsForm" label-width="120px">
                <el-form-item label="主题模式">
                  <el-radio-group v-model="settingsForm.theme">
                    <el-radio label="light">浅色模式</el-radio>
                    <el-radio label="dark">深色模式</el-radio>
                    <el-radio label="auto">跟随系统</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="语言设置">
                  <el-select v-model="settingsForm.language" placeholder="请选择语言">
                    <el-option label="简体中文" value="zh-CN" />
                    <el-option label="English" value="en-US" />
                  </el-select>
                </el-form-item>
                <el-form-item label="学习提醒">
                  <el-switch v-model="settingsForm.studyReminder" />
                </el-form-item>
                <el-form-item label="邮件通知">
                  <el-switch v-model="settingsForm.emailNotification" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="saveSettings">保存设置</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="showPasswordDialog" title="修改密码" width="400px">
      <el-form :model="passwordForm" label-width="100px">
        <el-form-item label="当前密码">
          <el-input v-model="passwordForm.oldPassword" type="password" />
        </el-form-item>
        <el-form-item label="新密码">
          <el-input v-model="passwordForm.newPassword" type="password" />
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input v-model="passwordForm.confirmPassword" type="password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPasswordDialog = false">取消</el-button>
        <el-button type="primary" @click="changePassword">确定</el-button>
      </template>
    </el-dialog>

    <!-- 更换头像对话框 -->
    <el-dialog v-model="showAvatarDialog" title="更换头像" width="400px">
      <div class="avatar-upload">
        <el-upload
          class="avatar-uploader"
          action="#"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="newAvatar" :src="newAvatar" class="avatar-preview" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </div>
      <template #footer>
        <el-button @click="showAvatarDialog = false">取消</el-button>
        <el-button type="primary" @click="updateAvatar">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  User, Lock, Reading, Trophy, Setting, Plus 
} from '@element-plus/icons-vue'

// 响应式数据
const activeMenu = ref('basic')
const updating = ref(false)
const showPasswordDialog = ref(false)
const showAvatarDialog = ref(false)
const newAvatar = ref('')

// 用户信息
const userInfo = ref({
  id: 1,
  username: 'student001',
  nickname: '学习者',
  email: 'student@example.com',
  phone: '13800138001',
  avatar: '',
  gender: 'UNKNOWN',
  birthday: null,
  bio: '',
  userType: 'STUDENT'
})

// 用户表单
const userForm = reactive({
  username: '',
  nickname: '',
  email: '',
  phone: '',
  gender: 'UNKNOWN',
  birthday: null,
  bio: ''
})

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 设置表单
const settingsForm = reactive({
  theme: 'light',
  language: 'zh-CN',
  studyReminder: true,
  emailNotification: true
})

// 统计数据
const statistics = ref({
  courseCount: 12,
  examCount: 8,
  studyHours: 156,
  points: 2580
})

const weeklyStats = ref({ hours: 8 })
const monthlyStats = ref({ hours: 32 })

// 最近课程
const recentCourses = ref([
  {
    id: 1,
    title: 'Vue.js 3.0 实战教程',
    cover: '/course-cover-1.jpg',
    progress: 75,
    lastStudyTime: '2024-01-15'
  },
  {
    id: 2,
    title: 'JavaScript 高级编程',
    cover: '/course-cover-2.jpg',
    progress: 45,
    lastStudyTime: '2024-01-14'
  }
])

// 成就徽章
const achievements = ref([
  {
    id: 1,
    name: '初学者',
    description: '完成第一门课程',
    icon: 'Reading',
    unlocked: true,
    unlockDate: '2024-01-10'
  },
  {
    id: 2,
    name: '勤奋学习者',
    description: '连续学习7天',
    icon: 'Trophy',
    unlocked: false
  }
])

// 方法
const handleMenuSelect = (index) => {
  activeMenu.value = index
}

const updateProfile = async () => {
  updating.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    Object.assign(userInfo.value, userForm)
    ElMessage.success('个人信息更新成功')
  } catch (error) {
    ElMessage.error('更新失败，请重试')
  } finally {
    updating.value = false
  }
}

const changePassword = async () => {
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    ElMessage.error('两次输入的密码不一致')
    return
  }
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('密码修改成功')
    showPasswordDialog.value = false
    Object.assign(passwordForm, {
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
  } catch (error) {
    ElMessage.error('密码修改失败')
  }
}

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }

  // 预览图片
  const reader = new FileReader()
  reader.onload = (e) => {
    newAvatar.value = e.target.result
  }
  reader.readAsDataURL(file)
  
  return false // 阻止自动上传
}

const updateAvatar = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    userInfo.value.avatar = newAvatar.value
    ElMessage.success('头像更新成功')
    showAvatarDialog.value = false
    newAvatar.value = ''
  } catch (error) {
    ElMessage.error('头像更新失败')
  }
}

const saveSettings = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElMessage.success('设置保存成功')
  } catch (error) {
    ElMessage.error('设置保存失败')
  }
}

const continueLearning = (course) => {
  ElMessage.success(`继续学习：${course.title}`)
  // 跳转到课程学习页面
}

const getUserTypeText = (type) => {
  const typeMap = {
    'STUDENT': '学生',
    'TEACHER': '教师',
    'ADMIN': '管理员'
  }
  return typeMap[type] || '用户'
}

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString()
}

// 页面加载
onMounted(() => {
  // 初始化表单数据
  Object.assign(userForm, userInfo.value)
})
</script>

<style lang="scss" scoped>
.profile-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.profile-header {
  margin-bottom: 20px;
}

.profile-card {
  .profile-info {
    display: flex;
    align-items: center;
    gap: 30px;
  }
  
  .avatar-section {
    text-align: center;
    position: relative;
    
    .change-avatar-btn {
      margin-top: 10px;
    }
  }
  
  .user-details {
    flex: 1;
    
    h2 {
      margin: 0 0 5px 0;
      color: #303133;
    }
    
    .user-title {
      color: #909399;
      margin: 0 0 20px 0;
    }
    
    .user-stats {
      display: flex;
      gap: 40px;
      
      .stat-item {
        text-align: center;
        
        .stat-number {
          display: block;
          font-size: 24px;
          font-weight: bold;
          color: #409eff;
        }
        
        .stat-label {
          font-size: 14px;
          color: #909399;
        }
      }
    }
  }
}

.profile-content {
  .menu-card {
    .profile-menu {
      border: none;
    }
  }
  
  .content-card {
    min-height: 600px;
    
    .content-section {
      h3 {
        margin-bottom: 20px;
        color: #303133;
        border-bottom: 2px solid #409eff;
        padding-bottom: 10px;
      }
    }
  }
}

.security-items {
  .security-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 0;
    border-bottom: 1px solid #ebeef5;
    
    &:last-child {
      border-bottom: none;
    }
    
    .security-info {
      h4 {
        margin: 0 0 5px 0;
        color: #303133;
      }
      
      p {
        margin: 0;
        color: #909399;
        font-size: 14px;
      }
    }
  }
}

.learning-stats {
  margin-bottom: 30px;
  
  .stat-card {
    text-align: center;
    padding: 20px;
    background: #f5f7fa;
    border-radius: 8px;
    
    h4 {
      margin: 0 0 10px 0;
      color: #606266;
    }
    
    .stat-value {
      margin: 0;
      font-size: 24px;
      font-weight: bold;
      color: #409eff;
    }
  }
}

.recent-courses {
  .course-item {
    display: flex;
    align-items: center;
    gap: 15px;
    padding: 15px 0;
    border-bottom: 1px solid #ebeef5;
    
    &:last-child {
      border-bottom: none;
    }
    
    .course-cover {
      width: 60px;
      height: 60px;
      border-radius: 8px;
      object-fit: cover;
    }
    
    .course-info {
      flex: 1;
      
      h5 {
        margin: 0 0 5px 0;
        color: #303133;
      }
      
      p {
        margin: 2px 0;
        font-size: 14px;
        color: #909399;
      }
    }
  }
}

.achievements-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  
  .achievement-item {
    text-align: center;
    padding: 20px;
    border: 1px solid #ebeef5;
    border-radius: 8px;
    
    .achievement-icon {
      margin-bottom: 10px;
      opacity: 0.3;
      
      &.unlocked {
        opacity: 1;
        color: #f6d55c;
      }
    }
    
    h5 {
      margin: 0 0 5px 0;
      color: #303133;
    }
    
    p {
      margin: 0 0 10px 0;
      font-size: 14px;
      color: #909399;
    }
    
    .unlock-date {
      font-size: 12px;
      color: #67c23a;
    }
  }
}

.avatar-upload {
  text-align: center;
  
  .avatar-uploader {
    :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: 0.2s;
      
      &:hover {
        border-color: #409eff;
      }
    }
  }
  
  .avatar-preview {
    width: 178px;
    height: 178px;
    display: block;
  }
  
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
}
</style>
